<?php 

namespace Admin\Controller;
use Api\Event\CacheEvent;
use Common\Util\ExcelOut;

class StatisController extends AdminController 
{
    /*
    <option value="video.play">视频播放</option>
    <option value="video.zan">视频点赞</option>
    <option value="video.comments">视频评论</option>
    <option value="video.submit">视频发布</option>
    <option value="app.download">应用下载</option>
    <option value="user.login">用户登录</option>
    <option value="user.register">用户注册</option>
     */
    static protected $stats_options = [
        'video.play'     => '视频播放',
        'video.zan'      => '视频点赞',
        'video.comments' => '视频评论',
        'video.submit'   => '视频播放',
        'app.download'   => '应用下载',
        'user.login'     => '用户登录',
        'video.register' => '用户注册',
    ];

    /**
     * 打赏统计
     * @return [type] [description]
     */
    public function reward()
    {
        $date = I('date', date('Y-m-d'), 'trim');

        // 次数  总额   人次
        $stat = D('Common/PayLog')->where(['type' => 'reward', 'date' => $date])->field('count(*) as count, sum(abs(money)) as total, count(distinct(uid)) as user')->find();
        $this->assign('date', $date);
        $this->assign('stat', $stat);
        $this->display();
    }

    // 统计报表
    public function chart()
    {
        if (IS_POST){
            $to   = I('to');
            $from = I('from');
            if (!$from){
                $from = date('Y-m-d', strtotime('-1 day'));
            }
            $data = [];
            $data['object_type'] = I('object_type');
            $data['object_compare'] = I('object_compare');

            if (empty($data['object_type'])){
                return $this->error('请选择报表类型');
            }

            // 判断
            if (in_array($data['object_type'], ['range', 'compare'])){
                if (empty($to)){
                    return $this->error('区间和对比必须选择结束时间');
                }
                if ($to <= $from){
                    return $this->error('结束时间必须大于开始时间');
                }

                if ($data['object_type'] == 'compare' && empty($data['object_compare']) ){
                    return $this->error('请选择对比项目');
                }
            }

            // $dates = $to ? range(date('Ymd', strtotime($from)), date('Ymd', strtotime($to))) : [date('Ymd', strtotime($from))];

            list($odate, $last) = $to ? [$from, $to] : [$from, $from];
            $yesterday = date('Y-m-d', strtotime('-1 day'));
            if ($last > $yesterday){
                $last = $yesterday;
            }
            $resServ = service('Statis/LogStatisItem');
            $results = [];
            $totals  = [];

            // $date = date('Y-m-d');
            // echo $date;
            // echo $last;
            do{
                $date = date('Ymd', strtotime($odate));
            // foreach ($dates as $date) {
                $res = $resServ->getDailyData($date);
                if ($res){
                    $results[$date] = $res;
                    $this->calcuTotal($res, $totals);
                }else{
                    $errors[] = $date;
                }
                $dates[] = $date;
                $odate = date('Y-m-d', strtotime("{$odate} +1 day"));
            // }
            }while($odate <= $last);
            $dates[] = "总和";
            $this->assign('dates', $dates);
            $results['总和'] = $totals;
            $this->assign('results', $results);
            $this->assign('totals', $totals);
            $this->assign('platforms', [0=>'Web', 1=> 'Android', 2=>'IOS', 5=>'Tool', 'total' => '合计']);
            // print_r($results);
            return $this->display('chart_result');
        }

        $this->assign('stats_options', self::$stats_options);
        $this->display();
    }

    protected function calcuTotal(&$result, &$totals)
    {
        foreach ($result as $platid => $platdata) {
            foreach ($platdata as $type => $items) {
                foreach ($items as $key => $value) {
                    foreach ($value as $class => $count) {
                        $totals[$platid][$type][$key][$class] += $count;
                    }
                }
            }
        }
    }

    public function index()
    {
        $date = date('Ymd', strtotime( I('date', date('Ymd')) ) );
        $Redis = CacheEvent::instance(7);
        $res = $Redis->hgetall("IMBA.STATIS.DAILY.$date");
        $statis = [];
        foreach ($res as $key => $value) {
            list($action, $platform) = explode('.', $key);
            $statis[$platform][$action] = $value;
        }
        $this->assign('date', date('Y-m-d', strtotime($date)) );
        $this->assign('statis', $statis);
        $platforms = ['Web', 'Android', 'IOS', 'Wp', 'Server', 'Tool'];
        $this->assign('platforms', $platforms);
        $this->display();
    }   


    public function video()
    {
        $from = I('from', date('Y-m-d', strtotime('-7 day')));
        $to   = I('to', date('Y-m-d'));

        $this->assign('from', $from);
        $this->assign('to', $to);

        // $query['$and'][]['create_time'] = ['$egt', $from];
        // $query['$and'][]['create_time'] = ['$elt', $to];

        $map['create_time'] = ['between', [strtotime($from), strtotime($to)+24*3600]];
        $map['status'] = 1;
        $map['race_id'] = array('egt', null);
        $map['type'] = 0;
        // $map['_array'] = $query;
        $video_ids = service('Video')->where($map)->getField('id', true);
        // echo service('Video')->_sql();
        $array[] = ['视频名称', '发布者', '游戏', '发布时间', '播放次数', '视频地址'];
        foreach ($video_ids as $id) {
            $video = event('Video')->detail($id);
            $array[] = [
                $video['title'],
                $video['user']['nickname'],
                $video['game']['name'],
                date('Y-m-d H:i',$video['create_time']),
                $video['statis']['play'],
                $video['uri']
            ];
        }
       
        if (IS_POST && I('export')){
            $ExcelOut = new ExcelOut('utf8', "视频发布统计|$from - $to");
            $ExcelOut->add_array($array);
            $ExcelOut->output();
            exit;
        }
        $this->display();
    }


    public function register()
    {
        $from = I('from', date('Y-m-d', strtotime('-7 day')));
        $to   = I('to', date('Y-m-d'));

        $this->assign('from', $from);
        $this->assign('to', $to);


        $map['reg_time'] = ['between', [strtotime($from), strtotime($to)+24*3600]];
        $users = service('Users')->where($map)->select();
        $stat = [];
        $daily = [];
        foreach ($users as $user) {
            $from = preg_match('/^[0-9]{11}$/', $user['username']) ? 'phone' : 'sso';
            $stat[$from]++;
            $regdate = date('Ymd', $user['reg_time']);
            $daily[$regdate]++;
        }
        $this->assign('stat', $stat);
        $this->assign('daily', $daily);
        print_r($daily);
        $this->display();

    }

    /**
     * 内部人员操作查询
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    public function inner() {

        $start = I('start', date('Y-m-d'));
        $end = I('end');
        $start_time = strtotime($start);

        if (empty($end)) {
            $end_time = $start_time + 24*60*60;
        } else {
            $end_time = strtotime($end) + 24*60*60;
        }

        $list = [];
        $likeService = service('like');
        $commentService = service('comments');
        $userService = service('users');

        $total = ['like' => 0, 'comment' => 0];
        $users = trim(C('INNER_USER_IDS'));
        if (!empty($users)) {
            $users = explode("\n", $users);
            foreach ($users as $u) {
                $u = explode('-', trim($u));
                $name = $u[0];
                $nickname = trim($u[1]);
                $user = $userService->where(['nickname' => $nickname])->find();
                $value = intval($user['id']);

                $lMap = ['uid' => intval($value), 'type' => 0];
                $lMap['create_time'] = ['between', [$start_time, $end_time]];
                $likeCount = $likeService->where($lMap)->count();

                $cMap = ['uid' => intval($value)];
                $cMap['create_time'] = ['between', [$start_time, $end_time]];
                $commentCount = $commentService->where($cMap)->count();

                $list[$value]['id'] = $value;
                $list[$value]['name'] = $name;
                $list[$value]['nickname'] = $user && $user['nickname'] ? $user['nickname'] : '';
                $list[$value]['like'] = $likeCount ?: 0;
                $list[$value]['comment'] = $commentCount ?: 0;
                $total['like'] += $list[$value]['like'];
                $total['comment'] += $list[$value]['comment'];
            }
        }
        $this->assign('result', $list);
        $this->assign('total',$total);
        $this->assign('start',$start);
        $this->assign('end',$end);

        $this->display();
    }


    public function reten()
    {
        $from = I('from', date('Y-m-d', strtotime('-9 day')));
        $to   = I('to', date('Y-m-d', strtotime('-2 day')));

        $this->assign('from', $from);
        $this->assign('to', $to);
        $date = $from;
        $retens = [];
        do{
            $retens[$date] = $this->getDailyReten($date);
            $date = date('Y-m-d', strtotime("$date +1 day"));
        }while($date <= $to);
        $this->assign('retens', $retens);
        $this->display();
    }

    protected function getDailyReten($date)
    {
        static $macs;
        static $new_macs;
        $days = 7;
        $model = service('ImbaLog/LogSource');
        $macdate = date('Ymd', strtotime($date));
        // 获取当日的新增
        if (!$new_macs[$date]){
            $new_macs[$date] = $model->table("imba_mac_new_{$macdate}")->getField('mac', true);
        }
        $i = 1;
        $next_date = date('Ymd', strtotime("$date +$i day"));
        $tody = date('Ymd');
        $reten = [];
        $new_count = count($new_macs[$date]);
        if ($new_count > 0)
        {
            while ($next_date < $tody && $i <= $days){
                $next_date = date('Ymd', strtotime("$date +$i day"));
                if (!$macs[$next_date]){
                    $macs[$next_date] = $model->table("imba_mac_daily_{$next_date}")->getField('mac', true);
                }
                $reten[$i] = count(array_intersect($macs[$next_date], $new_macs[$date]))/$new_count;
                $i++;
            }
        }
        return [$new_count, $reten];
    }

    /**
     * 发布统计  按照两个月
     * @return [type] [description]
     */
    public function uploader($uid)
    {
        $map = [
            'uid'           => (int)$uid,
            // 'create_time'   => ['egt', strtotime(date('Y-m-d')." -2 month")],
        ];
        $videos = service('Video')->where($map)->select();
        $stat = [];
        foreach ($videos as $video) {
            $day = date('Ymd', $video['create_time']);
            $stat[$day]++;
        }
        krsort($stat);
        $this->uid = $uid;
        $this->stat = $stat;
        $this->display();
    }


}